package com.graduation.lastproject.util.shiro;

import com.graduation.lastproject.entity.Admin;
import com.graduation.lastproject.service.admin.AdminBasicActive.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class AdminRealm extends AuthorizingRealm {
    private Logger logger= LoggerFactory.getLogger(AdminRealm.class);

    @Autowired
    private AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //*授予角色 解决消费者、商家登录成功后 admin请求没有拦截*//
        Set<String> set=new HashSet<>();
        set.add("admin");
        authorizationInfo.setRoles(set);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //把AuthenticationToken转换为LoginsToken
        LoginsToken loginsToken=(LoginsToken)authenticationToken;
        //获取的登录名
        String loginsname= (String) loginsToken.getPrincipal();
        //根据登录名查找数据库 t_bs_admin
        Admin admin=adminService.getAdminInfoByName(loginsname);
        if(admin!=null){
            SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo("",admin.getApassword(),"admin");
            logger.info("authenticationInfo保存对象:--------"+authenticationInfo);
            logger.info("session对象:--------"+admin);
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute("adminInfo",admin);
            session.setAttribute("admin",admin.getArealname());
            return  authenticationInfo;
        }
        return null;
    }


}
